<?php
namespace YDCMS\models;

class User
{
    private $db;
    private $id;
    private $username;
    private $email;
    private $password;
    private $role;
    private $created_at;
    private $updated_at;

    public function __construct()
    {
        $this->db = new \PDO(
            "mysql:host=" . $_ENV['DB_HOST'] . ";dbname=" . $_ENV['DB_NAME'],
            $_ENV['DB_USER'],
            $_ENV['DB_PASS']
        );
        $this->db->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
    }

    public function findByUsername($username)
    {
        $stmt = $this->db->prepare("SELECT * FROM yd_users WHERE username = ?");
        $stmt->execute([$username]);
        return $stmt->fetch(\PDO::FETCH_ASSOC);
    }

    public function findByEmail($email)
    {
        $stmt = $this->db->prepare("SELECT * FROM yd_users WHERE email = ?");
        $stmt->execute([$email]);
        return $stmt->fetch(\PDO::FETCH_ASSOC);
    }

    public function findById($id)
    {
        $stmt = $this->db->prepare("SELECT * FROM yd_users WHERE id = ?");
        $stmt->execute([$id]);
        return $stmt->fetch(\PDO::FETCH_ASSOC);
    }

    public function hasRole($userId, $roleName)
    {
        $sql = "SELECT COUNT(*) FROM yd_user_roles ur 
                JOIN yd_roles r ON ur.role_id = r.id 
                WHERE ur.user_id = ? AND r.name = ?";
        
        $stmt = $this->db->prepare($sql);
        $stmt->execute([$userId, $roleName]);
        
        return (int)$stmt->fetchColumn() > 0;
    }

    public function verifyPassword($password, $hashedPassword)
    {
        return password_verify($password, $hashedPassword);
    }

    public function create($username, $email, $password, $role = 'user')
    {
        $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
        
        $this->db->beginTransaction();
        
        try {
            // 创建用户
            $stmt = $this->db->prepare("
                INSERT INTO yd_users (username, email, password, created_at)
                VALUES (?, ?, ?, NOW())
            ");
            
            $stmt->execute([$username, $email, $hashedPassword]);
            $userId = $this->db->lastInsertId();
            
            // 获取角色ID
            $stmt = $this->db->prepare("SELECT id FROM yd_roles WHERE name = ?");
            $stmt->execute([$role]);
            $roleId = $stmt->fetchColumn();
            
            // 分配角色
            if ($roleId) {
                $stmt = $this->db->prepare("
                    INSERT INTO yd_user_roles (user_id, role_id)
                    VALUES (?, ?)
                ");
                $stmt->execute([$userId, $roleId]);
            }
            
            $this->db->commit();
            return true;
        } catch (\Exception $e) {
            $this->db->rollBack();
            throw $e;
        }
    }

    public function update($id, $data)
    {
        $fields = [];
        $values = [];
        
        foreach ($data as $key => $value) {
            if ($key === 'password') {
                $value = password_hash($value, PASSWORD_DEFAULT);
            }
            $fields[] = "$key = ?";
            $values[] = $value;
        }
        
        $values[] = $id;
        
        $sql = "UPDATE yd_users SET " . implode(', ', $fields) . ", updated_at = NOW() WHERE id = ?";
        $stmt = $this->db->prepare($sql);
        
        return $stmt->execute($values);
    }

    public function delete($id)
    {
        $stmt = $this->db->prepare("DELETE FROM yd_users WHERE id = ?");
        return $stmt->execute([$id]);
    }
} 